package huriezy.quickcontacts.activities.fragments;

import huriezy.quickcontacts.R;
import huriezy.quickcontacts.models.ContactController;
import huriezy.quickcontacts.models.LogDebug;
import huriezy.quickcontacts.models.interfaces.IContactManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;

public class EmailFragment extends ContactFragment {

	private String				lastUsedSuffix	= null;

	public static EmailFragment newInstance(String email) {
		EmailFragment instance = new EmailFragment();
		Bundle args = new Bundle();
		args.putString(IContactManager.EMAIL_TAG, email);
		instance.setArguments(args);
		return instance;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		View result = inflater.inflate(R.layout.fragment_email, container, false);
		Bundle args = getArguments();
		if (args == null) {
			args = savedInstanceState;
			LogDebug.info(" * Use savedInstanceState for " + getClass().getSimpleName(), getClass());
		}
		else {
			LogDebug.info(" * Use newInstance bundle for " + getClass().getSimpleName(), getClass());
		}
		if (args != null) {
			String email = args.getString(IContactManager.EMAIL_TAG);
			setEmail(email,result);
		}
		else {
			LogDebug.debug("No saved informations.", getClass());
		}

		RadioButton localeSuffixRadioButton = (RadioButton) result.findViewById(R.id.locale_suffix_radiobutton);
		String localeLanguage = getActivity().getResources().getConfiguration().locale.getLanguage();
		if (localeSuffixRadioButton != null && localeLanguage != null && localeLanguage.length() > 0) {
			localeSuffixRadioButton.setText("." + localeLanguage);
		}

		initActions(result);

		return result;
	}

	@Override
	public void clearContactData() {
		setEmail("", getView());
	}

	@Override
	public void saveContactData() {
		IContactManager contactManager = ContactController.getInstance().getContactManager(getActivity());
		contactManager.putContactData(IContactManager.EMAIL_TAG, getEmail(getView()));
	}

	/**
	 * Init this fragment actions
	 */
	private void initActions(View parentView) {
		ImageButton yahooButton = (ImageButton) parentView.findViewById(R.id.use_yahoo_button);
		if (yahooButton != null) {
			yahooButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					updateEmailTextView(getResources().getString(R.string.email_yahoo_suffix_text));
				}
			});
		}

		ImageButton gmailButton = (ImageButton) parentView.findViewById(R.id.use_gmail_button);
		if (gmailButton != null) {
			gmailButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					updateEmailTextView(getResources().getString(R.string.email_gmail_suffix_text));
				}
			});
		}

		ImageButton hotmailButton = (ImageButton) parentView.findViewById(R.id.use_hotmail_button);
		if (hotmailButton != null) {
			hotmailButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					updateEmailTextView(getResources().getString(R.string.email_hotmail_suffix_text));
				}
			});
		}

		OnClickListener listener = new OnClickListener() {
			@Override
			public void onClick(View v) {
				updateEmailTextView(null);
			}
		};

		RadioButton comSuffixRadioButton = (RadioButton) parentView.findViewById(R.id.com_suffix_radiobutton);
		if (comSuffixRadioButton != null) {
			comSuffixRadioButton.setOnClickListener(listener);
		}

		RadioButton localeSuffixRadioButton = (RadioButton) parentView.findViewById(R.id.locale_suffix_radiobutton);
		if (localeSuffixRadioButton != null) {
			localeSuffixRadioButton.setOnClickListener(listener);
		}
	}

	/**
	 * Update the text contained in the email {@link EditText} view using the
	 * donate suffix.
	 * 
	 * @param providerSuffix
	 */
	private void updateEmailTextView(String providerSuffix) {

		EditText emailEdittext = (EditText) getView().findViewById(R.id.contact_email_editText);
		if (emailEdittext != null) {
			// Verify if the edit text view already contains informations
			String emailContent = emailEdittext.getText().toString();

			// Get selected locale suffix using the suffix radiogroup
			String countrySuffix = null;
			RadioGroup group = (RadioGroup) getView().findViewById(R.id.suffix_radiogroup);
			if (group != null) {
				int radioId = group.getCheckedRadioButtonId();
				RadioButton checkedRadioButton = (RadioButton) getView().findViewById(radioId);
				if (checkedRadioButton != null) {
					countrySuffix = checkedRadioButton.getText().toString();
				}
			}

			String result = buildNewMailAdress(emailContent, providerSuffix, countrySuffix);

			// Update the content of the edit text
			if (result != null) {
				emailEdittext.setText(result);
			}
		}
	}

	private String buildNewMailAdress(String emailContent, String providerSuffix, String countrySuffix) {
		StringBuilder result = new StringBuilder();
		if (emailContent != null && emailContent.length() > 0) {
			LogDebug.info("email content : " + emailContent, getClass());
			String[] splitMailAddress = emailContent.split("@");
			String emailFirstPart = null;
			if (splitMailAddress != null && splitMailAddress.length > 0) {
				for (String elem : splitMailAddress) {
					LogDebug.info("Split elem : " + elem, getClass());
				}
				// If the content has a '@' symbol, we take only the first
				// part
				emailFirstPart = splitMailAddress[0];
			}
			else {
				// Else we take all the content
				emailFirstPart = emailContent;
			}
			if (emailFirstPart != null && emailFirstPart.length() > 0) {
				LogDebug.info("email first part : " + emailFirstPart, getClass());
				result.append(emailFirstPart);
			}
		}
		result.append("@");
		if (providerSuffix == null) {
			providerSuffix = lastUsedSuffix;
		}
		if (providerSuffix != null) {
			result.append(providerSuffix);
			lastUsedSuffix = providerSuffix;
		}
		else {
			// If no previous suffix, no update is make
			return null;
		}

		if (countrySuffix != null) {
			result.append(countrySuffix);
		}

		return result.toString();
	}

	public void setEmail(String email, View view) {
		EditText edittext = getEmailEditText(view);
		if (edittext != null) {
			edittext.setText(email);
		}
	}

	public String getEmail(View view) {
		String result = "";
		EditText edittext = getEmailEditText(view);
		if (edittext != null) {
			result = edittext.getText().toString();
		}
		return result;
	}

	private EditText getEmailEditText(View view) {
		if (view != null) {
			return (EditText) view.findViewById(R.id.contact_email_editText);
		}
		else {
			LogDebug.warn("No Edit text view founded for contact email.", getClass());
		}
		return null;
	}
}
